package com.shi.yoyoshop.controller;

import com.shi.yoyoshop.bean.Goods;
import com.shi.yoyoshop.bean.Type;
import com.shi.yoyoshop.service.GoodsService;
import com.shi.yoyoshop.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class TypeController {

    @Resource
    private TypeService typeService;

    @Resource
    private GoodsService goodsService;

    @GetMapping("/admin/typeList")
    public String searchTypeList(HttpServletRequest request) {
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList", typeList);
        return "/admin/type_list.jsp";
    }

    @PostMapping("/admin/typeAdd")
    public String addType(String name) {
        Type type = new Type();
        type.setName(name);
        type.setStatus(1);
        typeService.save(type);
        return "redirect:/admin/typeList";
    }

    @GetMapping("/admin/typeEdit")
    public String toEditType(HttpServletRequest request, Integer id) {
        Type type = typeService.getOneByTypeId(id);
        request.setAttribute("type", type);
        return "/admin/type_edit.jsp";
    }

    @PostMapping("/admin/typeEdit")
    public String editType(Integer id, String name) {
        Type type = new Type();
        type.setId(id);
        type.setName(name);
        typeService.updateById(type);
        return "redirect:/admin/typeList";
    }

    @GetMapping("/admin/typeDelete")
    public String removeType(HttpServletRequest request, Integer id) {
        // 判断该类型是否有对应的商品，如果有则不能删除
        List<Goods> goodsList = goodsService.getGoodsListByTypeId(id);
        if (!CollectionUtils.isEmpty(goodsList)) {
            request.setAttribute("msg", "该类型下有商品存在，不能删除！");
            List<Type> typeList = typeService.getTypeList();
            request.setAttribute("typeList", typeList);
            return "/admin/type_list.jsp";
        }
        Type type = new Type();
        type.setId(id);
        type.setStatus(0);
        typeService.updateById(type);
        return "redirect:/admin/typeList";
    }
}
